package com.gly091020.GLYCan.client;

import com.gly091020.GLYCan.GLYCanMod;
import com.gly091020.GLYCan.block.CanBlock;
import com.gly091020.GLYCan.block.entity.CanBlockEntity;
import com.gly091020.GLYCan.item.CanItem;
import com.gly091020.GLYCan.util.CanComponent;
import com.gly091020.GLYCan.util.CanItemContainer;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BlockEntityWithoutLevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.block.BlockRenderDispatcher;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher;
import net.minecraft.core.BlockPos;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.api.distmarker.OnlyIn;

@OnlyIn(Dist.CLIENT)
public class CanItemRenderer extends BlockEntityWithoutLevelRenderer {
    public static BlockRenderDispatcher BLOCK_RENDERER;
    public static CanBlockEntity ENTITY;
    private BlockEntityRenderDispatcher blockEntityRenderDispatcher;
    public static CanBlockColors colors = new CanBlockColors();

    public CanItemRenderer() {
        super(Minecraft.getInstance().getBlockEntityRenderDispatcher(), Minecraft.getInstance().getEntityModels());
        blockEntityRenderDispatcher = Minecraft.getInstance().getBlockEntityRenderDispatcher();
        BLOCK_RENDERER = new BlockRenderDispatcher(Minecraft.getInstance().getBlockRenderer().getBlockModelShaper(), new BlockEntityWithoutLevelRenderer(blockEntityRenderDispatcher, Minecraft.getInstance().getEntityModels()), colors);
    }

    @Override
    public void renderByItem(ItemStack itemStack, ItemDisplayContext context, PoseStack poseStack, MultiBufferSource bufferSource, int i, int i1) {
        if(ENTITY == null){
            ENTITY = new CanBlockEntity(BlockPos.ZERO, GLYCanMod.CAN_BLOCK.get().defaultBlockState());
        }
        if(blockEntityRenderDispatcher == null){
            blockEntityRenderDispatcher = Minecraft.getInstance().getBlockEntityRenderDispatcher();
        }
        var item = itemStack.getItem();
        var d = itemStack.getOrDefault(GLYCanMod.CAN_COMPONENTS,
                new CanComponent(false, CanBlock.NORMAL_COLOR));
        ENTITY.color = d.color();
        colors.color = d.color();
        if(item instanceof CanItem){
            ENTITY.setBlockState(ENTITY.getBlockState().setValue(CanBlock.IS_TETO, d.isTeto()));
            BLOCK_RENDERER.renderSingleBlock(ENTITY.getBlockState(), poseStack, bufferSource, i, i1, ENTITY.getModelData(), RenderType.CUTOUT);
            ENTITY.setItems(new CanItemContainer(itemStack).getItems());
            blockEntityRenderDispatcher.renderItem(ENTITY, poseStack, bufferSource, i, i1);
        }
    }
}
